package com.chucang.shucang.auth.support.handler;

import cn.hutool.core.text.CharSequenceUtil;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.base.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/15 20:35
 * @description 授权失败处理
 */
@Slf4j
public class ShuCangAuthenticationFailureEventHandler implements AuthenticationFailureHandler {

    private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String username;
        if (CharSequenceUtil.isBlank(request.getParameter(SecurityConstant.SMS_PARAMETER_NAME))) {
            username = request.getParameter(SecurityConstant.USERNAME);
        } else {
            username = request.getParameter(SecurityConstant.SMS_PARAMETER_NAME);
        }

        log.info("用户：{} 登录失败，异常：{}", username, exception.getLocalizedMessage());
        //TODO 记录日志信息
        //SpringUtil.publishEvent();
        // 写出错误信息
        this.sendErrorResponse(response, exception);
    }

    private void sendErrorResponse(HttpServletResponse response, AuthenticationException exception) throws IOException {
        ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
        httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        this.errorHttpResponseConverter.write(R.failed(exception.getLocalizedMessage()), MediaType.APPLICATION_JSON,
                httpResponse);
    }
}
